<template>
  <div>
    <div class="printBox">
      <iframe :src="printUrl" width="100%" :height="pdfHeight"/>
      <div v-if="loading" class="printItem" ref="printContent" id="printContent">
        <div class="printTitleTop" :style="{ fontSize: conditionData.titleSize }">
          {{ dataList[conditionData.titleKey] }}
        </div>
        <div class="printTitle" :style="{ fontSize: conditionData.titleSize, padding: '0 0 30px 0' }">
          {{ conditionData.memo }}
        </div>
        <a-row class="printRow" :style="{ fontSize: conditionData.mainListSize }" v-for="(item, index) in conditionData.mainList" :key="index">
          <a-col v-for="(items, indexs) in item.colList" :key="indexs" :span="24 / item.colList.length">
            {{ items.label }}
            {{ dataList[items.title] }}
          </a-col>
        </a-row>
        <a-table :class="conditionData.tableFontSize" :bordered="conditionData.border"
                 :pagination="false"
                 :rowKey="(record, index) => { return index }"
                 :columns="conditionData.columnList" :data-source="dataList.tableData" :size="conditionData.size">
        </a-table>
        <a-row class="printRow bottomRow" :style="{ fontSize: conditionData.bottomListSize }" v-for="(item, index) in conditionData.bottomList" :key="index">
          <a-col v-for="(items, indexs) in item.colList" :key="indexs" :span="24 / item.colList.length">
            {{ items.label }}
            {{ dataList[items.title] }}
          </a-col>
        </a-row>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

export default {
  name: "PrintLayout",
  components: {},
  data() {
    return {
      pdfHeight: window.innerHeight - 6,
      loading: true,
      projectId: '',
      configId: '',
      printId: '',
      printUrl: '',
      dataList: {},
      conditionData: {}
    };
  },
  created() {
    this.projectId = this.$route.params.projectId;
    this.configId = this.$route.params.configId;
    this.printId = this.$route.params.printId;
  },
  mounted() {
    this.loadConditions();
  },
  // 监听路由发生变化时刷新信息
  watch: {},
  methods: {
    // 获取数据
    loadConditions() {
      axios
          .get("/print/" +
              this.projectId +
              "/" +
              this.configId +
              "/" +
              this.printId +
              "/getPrintConfigAndData"
          )
          .then(resp => {
            if (resp.data.code === "500") {
              alert(resp.data.data);
            } else {
              if (resp.data.data.printConfig) {
                const columnBox = resp.data.data.printConfig;
                for (let i = 0; i < columnBox.columnList.length; i++) {
                  if (columnBox.columnList[i].merge) {
                    columnBox.columnList[i].customRender = (text, row, index) => {
                      const obj = {
                        children: text,
                        attrs: {}
                      }
                      const data = this.dataList.tableData;
                      obj.attrs.rowSpan = this.getRowSpanCount(data || [], columnBox.columnList[i].dataIndex, index)
                      return obj
                    }
                  }
                }
                this.conditionData = columnBox;
                this.$nextTick(() => {
                  this.generatePDF()
                });
              }
              if (resp.data.data.printData) {
                this.dataList = resp.data.data.printData;
              }
            }
          });
    },
    // 合并列
    getRowSpanCount(data, key, target) {
      if (!Array.isArray(data)) return 1;
      data = data.map(_ => _[key]); // 只取出筛选项
      let preValue = data[0];
      const res = [[preValue]]; // 放进二维数组里
      let index = 0; // 二维数组下标
      for (let i = 1; i < data.length; i++) {
        if (data[i] === preValue) { // 相同放进二维数组
          res[index].push(data[i]);
        } else { // 不相同二维数组下标+1
          index += 1;
          res[index] = [];
          res[index].push(data[i]);
          preValue = data[i];
        }
      }
      const arr = [];
      res.forEach((_) => {
        const len = _.length;
        for (let i = 0; i < len; i++) {
          arr.push(i === 0 ? len : 0);
        }
      });
      return arr[target];
    },
    // 生成pdf
    generatePDF() {
      const content = this.$refs.printContent;
      html2canvas(content).then(canvas => {
        // 因为获取pdf高度需要pdf方法，故写此方法获取pdfHeightGet
        const imgDataGet = canvas.toDataURL("image/png");
        const pdfGet = new jsPDF({
          orientation: 'portrait',
          unit: 'px',
          format: [this.conditionData.pageWidth, 1000]
        });
        const imgPropsGet = pdfGet.getImageProperties(imgDataGet);
        const pdfWidthGet = pdfGet.internal.pageSize.getWidth();
        const pdfHeightGet = (imgPropsGet.height * pdfWidthGet) / imgPropsGet.width;

        const imgData = canvas.toDataURL("image/png");
        const pdf = new jsPDF({
          orientation: 'portrait',
          unit: 'px',
          format: [this.conditionData.pageWidth, pdfHeightGet]
        });
        pdf.internal.printingPressResolution = 300;
        const imgProps = pdf.getImageProperties(imgData);
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
        console.log(pdfHeightGet, pdfHeight)

        // 分页
        // let contentWidth = canvas.width;
        // let contentHeight = canvas.height;
        // let pageHeight = contentWidth / 595.28 * 841.89;  // 一页pdf显示html页面生成的canvas高度;
        // let leftHeight = contentHeight;  //未生成pdf的html页面高度
        // let position = 0;  // pdf页面偏移
        // // a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
        // let imgWidth = pdf.internal.pageSize.getWidth();
        // let imgHeight = (imgProps.height * pdfWidth) / imgProps.width;
        // if (leftHeight < pageHeight) {
        //   pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
        // } else {
        //   while (leftHeight > 0) {
        //     pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
        //     leftHeight -= pageHeight;
        //     position -= 632.89;
        //     // 避免添加空白页
        //     if (leftHeight > 0) {
        //       pdf.addPage();
        //     }
        //   }
        // }

        // 下载
        if (this.conditionData.printType === 'download') {
          pdf.save('download.pdf');// 下载创建一个新的jsPDF实例
        }
        // 预览
        if (this.conditionData.printType === 'preview') {
          // 转换PDF为数据URL
          const pdfBlob = pdf.output('blob');
          const pdfUrl = URL.createObjectURL(pdfBlob);
          this.printUrl = pdfUrl;
          // window.open(pdfUrl);
        }
        this.loading = false;
      });
    }
  },
};
</script>

<style scoped>
* {
  font-family: Microsoft YaHei !important;
  color: #000000 !important;
}

/deep/ .ant-table {
  color: #000000 !important;
}

/deep/ .ant-table-thead > tr > th {
  color: #000000 !important;
}

.printItem {
  padding: 40px;
}

.printTitleTop {
  text-align: center;
}

.printTitle {
  font-weight: bold;
  text-align: center;
}

.printRow {
  margin-bottom: 15px;
}

.bottomRow {
  margin-top: 15px;
}

/deep/ tr th {
  background: #FFFFFF!important;
  border: 2px solid black!important;
}

/deep/ tr td {
  border: 2px solid black!important;
}

/deep/ table {
  border-right: 2px solid black!important;
  border-bottom: 2px solid black!important;
}

/deep/ .ant-table-small > .ant-table-content > .ant-table-body {
  margin: 0!important;
}

/deep/.tableFontSize30 th {
  font-size: 30px !important;
}

/deep/.tableFontSize30 td {
  font-size: 30px !important;
}

/deep/.tableFontSize40 th {
  font-size: 40px !important;
}

/deep/.tableFontSize40 td {
  font-size: 40px !important;
}

/deep/.tableFontSize50 th {
  font-size: 50px !important;
}

/deep/.tableFontSize50 td {
  font-size: 50px !important;
}

@media print {
  #printContent {
    font-family: Microsoft YaHei !important;
    color: #000000 !important;
  }
}
</style>
